from django.db import models

# Create your models here.
from django.contrib.auth.models import User
from django.utils import timezone
from django.urls import reverse

from django_ckeditor_5.fields import CKEditor5Field


class Category(models.Model):
    class Meta:
        verbose_name = "分类"
        verbose_name_plural = verbose_name

    category = models.CharField(max_length=20)

    def __str__(self):
        return self.category


class Tag(models.Model):
    class Meta:
        verbose_name = "标签"
        verbose_name_plural = verbose_name

    tag = models.CharField(max_length=20)

    def __str__(self):
        return self.tag


class Article(models.Model):
    class Meta:
        verbose_name = "博客文章"
        verbose_name_plural = verbose_name
        ordering = ('-createTime',)

    id = models.AutoField(primary_key=True)
    title = models.CharField("标题", max_length=100)
    content = CKEditor5Field("正文", config_name='extends')
    createTime = models.DateTimeField("创建时间", default=timezone.now)
    updateTime = models.DateTimeField("修改时间", auto_now=True)
    postedBy = models.ForeignKey(User, verbose_name="发布者", on_delete=models.CASCADE)
    author = models.CharField(verbose_name="作者", max_length=50)
    category = models.ForeignKey(Category, verbose_name="分类", on_delete=models.CASCADE, blank=True, null=True)
    tags = models.ManyToManyField(Tag, verbose_name="标签", blank=True)
    views = models.PositiveIntegerField("阅读次数", default=0, editable=False)
    coverImage = models.ImageField("封面图", upload_to="cover", default="", help_text="最佳尺寸：256 x 256")

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('article:detail', kwargs={'pk': self.pk})

    def increase_views(self):
        self.views += 1
        self.save(update_fields=['views'])
